#!/usr/bin/env python

# Copyright (c) 2009 Olexandr Melnyk <me@omelnyk.net>
# See COPYING for details.

import sys
import os
import imp
import getopt
import re

import irclib
import libpolybot
import botconfig

# Load dictionaries from "./dicts" subdirectory
dict_path = sys.path[0] + "/dicts"
dicts = {}
for a_dict in os.listdir(dict_path):
    if re.match('^[^.]', a_dict):
        filename = os.path.splitext(a_dict)[0]
        parts = filename.split("-")
        module_name = "".join(part.title() for part in parts)
        mod = imp.load_source(module_name, dict_path + "/" + a_dict)
        class_name = module_name + "Dictionary"
        dicts[module_name] = getattr(mod, class_name)()

# Load default connection options
server   = botconfig.server
port     = botconfig.port
channels = botconfig.channels
nick     = botconfig.nick
name     = botconfig.name

# Parse command line arguments
optlist, optlist2 = getopt.getopt(sys.argv[1:], "s:p:c:n:")
for name, value in optlist:
    if name == "-s":
        server = value
    elif name == '-p':
        port = int(value)
    elif name == "-c":
        channels = value.split(",")
    elif name == "-n":
        nick = value
    else:
        print "Illegal command line argument: ", name
        exit

# Connect bot to the server, join the channels and wait for messages
try:
    print "Connecting to %s:%d" % (server, port)
    bot = libpolybot.Polybot(dicts, sys.stdout, server, port, nick, name)
    for channel in channels:
        print "Joining ", channel
        bot.join(channel)
    bot.event_loop()
except irclib.ServerConnectionError:
    print "Could not connect to", network
